<?php
session_start();
// 仅admin和管理组可访问
if (!isset($_SESSION['username']) || !isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'manager'])) {
    header('Location: login.php');
    exit();
}

// 用户数据文件
$user_file = 'users.json';
if (!file_exists($user_file)) file_put_contents($user_file, json_encode([]));
$users = json_decode(file_get_contents($user_file), true);

// 处理添加用户请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_user') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $role = $_POST['role'] ?? 'query';
    if ($username && $password && in_array($role, ['manager', 'query'])) {
        // 检查用户名是否已存在
        foreach ($users as $u) {
            if ($u['username'] === $username) {
                echo json_encode(['success' => false, 'message' => '用户名已存在']);
                exit();
            }
        }
        $users[] = [
            'username' => $username,
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'role' => $role
        ];
        file_put_contents($user_file, json_encode($users, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
        echo json_encode(['success' => true]);
        exit();
    } else {
        echo json_encode(['success' => false, 'message' => '请填写完整信息']);
        exit();
    }
}

// 处理编辑用户请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_user') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $role = $_POST['role'] ?? 'query';
    $found = false;
    foreach ($users as &$u) {
        if ($u['username'] === $username) {
            if ($password) $u['password'] = password_hash($password, PASSWORD_DEFAULT);
            $u['role'] = $role;
            $found = true;
            break;
        }
    }
    if ($found) {
        file_put_contents($user_file, json_encode($users, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => '用户不存在']);
    }
    exit();
}

// 处理删除用户请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_user') {
    $username = trim($_POST['username'] ?? '');
    $new_users = [];
    $found = false;
    foreach ($users as $u) {
        if ($u['username'] === $username) {
            $found = true;
            continue;
        }
        $new_users[] = $u;
    }
    if ($found) {
        file_put_contents($user_file, json_encode($new_users, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => '用户不存在']);
    }
    exit();
}

?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f0f2f5; margin: 0; padding: 0; }
        .container { max-width: 600px; margin: 40px auto; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); padding: 32px; }
        h2 { margin-top: 0; }
        .form-group { margin-bottom: 16px; }
        label { display: block; margin-bottom: 6px; }
        input, select { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        button { background: #1677ff; color: #fff; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; }
        button:hover { background: #4096ff; }
        table { width: 100%; border-collapse: collapse; margin-top: 24px; }
        th, td { border: 1px solid #eee; padding: 8px; text-align: left; }
        th { background: #fafafa; }
        .role-manager { color: #1677ff; font-weight: bold; }
        .role-query { color: #52c41a; font-weight: bold; }
        .msg { margin-bottom: 16px; color: #ff4d4f; }
    </style>
</head>
<body>
<div class="container">
    <h2>用户管理</h2>
    <div id="msg" class="msg"></div>
    <form id="add-user-form" autocomplete="off">
        <div class="form-group">
            <label>用户名</label>
            <input type="text" name="username" required>
        </div>
        <div class="form-group">
            <label>密码</label>
            <input type="password" name="password" required>
        </div>
        <div class="form-group">
            <label>权限</label>
            <select name="role">
                <option value="manager">管理组</option>
                <option value="query">查询组</option>
            </select>
        </div>
        <button type="submit">添加用户</button>
    </form>
    <table>
        <tr><th>用户名</th><th>权限</th><th>操作</th></tr>
        <?php foreach ($users as $u): ?>
        <tr>
            <td><?php echo htmlspecialchars($u['username']); ?></td>
            <td class="role-<?php echo $u['role']; ?>">
                <?php echo $u['role'] === 'manager' ? '管理组' : ($u['role'] === 'admin' ? '管理员' : '查询组'); ?>
            </td>
            <td>
                <button onclick="showEditUser('<?php echo htmlspecialchars($u['username']); ?>','<?php echo $u['role']; ?>')">编辑</button>
                <?php if ($u['username'] !== 'admin'): ?>
                <button onclick="deleteUser('<?php echo htmlspecialchars($u['username']); ?>')">删除</button>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    <a href="index.php" style="display:inline-block;margin-top:20px;color:#1677ff;">返回首页</a>

    <!-- 编辑用户模态框 -->
    <div id="editUserModal" style="display:none;position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.2);z-index:999;align-items:center;justify-content:center;">
        <div style="background:#fff;padding:24px 32px;border-radius:8px;min-width:320px;max-width:90vw;">
            <h3>编辑用户</h3>
            <form id="edit-user-form" autocomplete="off">
                <input type="hidden" name="username" id="edit-username">
                <div class="form-group">
                    <label>用户名</label>
                    <input type="text" id="edit-username-show" disabled>
                </div>
                <div class="form-group">
                    <label>新密码（留空则不修改）</label>
                    <input type="password" name="password" id="edit-password">
                </div>
                <div class="form-group">
                    <label>权限</label>
                    <select name="role" id="edit-role">
                        <option value="manager">管理组</option>
                        <option value="query">查询组</option>
                    </select>
                </div>
                <div style="text-align:right;">
                    <button type="button" onclick="closeEditUser()" style="margin-right:12px;">取消</button>
                    <button type="submit">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- Toast提示框 -->
<div id="toast" style="display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:9999;min-width:180px;padding:18px 32px;background:rgba(0,0,0,0.85);color:#fff;border-radius:8px;font-size:18px;box-shadow:0 2px 12px rgba(0,0,0,0.18);text-align:center;pointer-events:none;transition:all 0.3s;"></div>
<script>
    // Toast函数
    function showToast(msg, type) {
        var toast = document.getElementById('toast');
        toast.innerText = msg;
        toast.style.background = type === 'error' ? 'rgba(255,77,79,0.95)' : 'rgba(0,0,0,0.85)';
        toast.style.display = 'block';
        clearTimeout(window.toastTimer);
        window.toastTimer = setTimeout(function(){ toast.style.display = 'none'; }, 3000);
    }
    // 添加用户表单事件
    document.getElementById('add-user-form').onsubmit = function(e) {
        e.preventDefault();
        var form = e.target;
        var data = new FormData(form);
        data.append('action', 'add_user');
        fetch('user_manage.php', {
            method: 'POST',
            body: data
        }).then(r => r.json()).then(res => {
            if(res.success) {
                showToast('添加成功', 'success');
                setTimeout(()=>location.reload(), 1000);
            } else {
                showToast(res.message, 'error');
            }
        });
    };

    function showEditUser(username, role) {
        document.getElementById('editUserModal').style.display = 'flex';
        document.getElementById('edit-username').value = username;
        document.getElementById('edit-username-show').value = username;
        document.getElementById('edit-password').value = '';
        document.getElementById('edit-role').value = role;
    }
    function closeEditUser() {
        document.getElementById('editUserModal').style.display = 'none';
    }
    document.getElementById('edit-user-form').onsubmit = function(e) {
        e.preventDefault();
        var form = e.target;
        var data = new FormData(form);
        data.append('action', 'edit_user');
        fetch('user_manage.php', {
            method: 'POST',
            body: data
        }).then(r => r.json()).then(res => {
            if(res.success) {
                showToast('修改成功', 'success');
                setTimeout(()=>location.reload(), 1000);
            } else {
                showToast(res.message, 'error');
            }
        });
    };
    function deleteUser(username) {
        if (!confirm('确定要删除用户 ' + username + ' 吗？')) return;
        var data = new FormData();
        data.append('action', 'delete_user');
        data.append('username', username);
        fetch('user_manage.php', {
            method: 'POST',
            body: data
        }).then(r => r.json()).then(res => {
            if(res.success) {
                showToast('删除成功', 'success');
                setTimeout(()=>location.reload(), 1000);
            } else {
                showToast(res.message, 'error');
            }
        });
    }
</script>
</body>
</html> 